﻿//https://leetcode.cn/problems/binary-tree-right-side-view/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root)
    {
        unordered_map<int, int> rightdepth;
        stack<TreeNode*> rootset;
        stack<int> depthset;
        rootset.push(root);
        depthset.push(0);
        int maxdepth = -1;
        while (!rootset.empty())
        {
            TreeNode* node = rootset.top();
            rootset.pop();
            int depth = depthset.top();
            depthset.pop();

            if (node)
            {
                maxdepth = max(maxdepth, depth);

                if (rightdepth.find(depth) == rightdepth.end())
                {
                    rightdepth[depth] = node->val;
                }

                rootset.push(node->left);
                rootset.push(node->right);
                depthset.push(depth + 1);
                depthset.push(depth + 1);
            }
        }

        vector<int> ret;
        for (int depth = 0; depth <= maxdepth; depth++)
        {
            ret.push_back(rightdepth[depth]);
        }

        return ret;
    }
};